package xju_5_6.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Controller
public class FileUploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String originalFilename = file.getOriginalFilename(); // 文件名称

        File file1 = new File(request.getSession().getServletContext().getRealPath("file"), originalFilename);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        file.transferTo(file1);
        return file1.getAbsolutePath();
    }

    @RequestMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        File file = new
                File(request.getSession().getServletContext().getRealPath("file"), "uninstallerIcon.ico");
        System.out.println("文件：" + file.getAbsolutePath());
        byte[] data = FileUtils.readFileToByteArray(file);
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment;filename=" + new
                String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.getOutputStream().write(data);
    }
}
